<template>
  <div class="main-content">
    <div class="scalable-container" :style="{ transform: `scale(${scale})`, transformOrigin: 'top' }">
      <!-- 页面内容 -->
      <div class="content">
        <div class="front-header">
          <div class="front-header-left">
            <div class="title">助教下载站</div>
          </div>
          <div class="front-header-center">
            <div class="front-header-nav">
              <el-menu :default-active="activeMenuIndex" mode="horizontal" router active-text-color="#2A60C9">
                <el-menu-item index="/front/homeFront">首页</el-menu-item>
                <!--                <el-menu-item @click="goDrive(item.id)" v-for="(item, i) in topName" :key="i">{{ item.name }}</el-menu-item>-->
                <el-menu-item index="/front/drive">驱动</el-menu-item>
                <el-menu-item index="/front/typeface">字体</el-menu-item>
                <el-menu-item index="/front/contact">关于我们</el-menu-item>

                <!--                <el-menu-item v-for="(item, index) in allMenuItemsComputed" :key="index" :index="item.index">{{ item.name }}</el-menu-item>-->

                <!--                <el-submenu v-if="moreMenuItems.length > 0" index="more" label="更多">-->
                <!--                  <el-menu-item-group>-->
                <!--                    <el-menu-item v-for="(item, index) in moreMenuItems" :key="index" :index="item.index">{{item.name}}</el-menu-item>-->
                <!--                  </el-menu-item-group>-->
                <!--                </el-submenu>-->

                <!--                <el-select style="width: 20px" v-model="topName">-->
                <!--                  <el-option v-for="item in topName" :key="item.id" :value="item.id" :label="item.name"></el-option>-->
                <!--                </el-select>-->

                <!--                <el-input :class="{'rounded-input': true}" prefix-icon="el-icon-search" v-model="name"-->
                <!--                          placeholder="在这里输入你要找的软件" style="width: 280px;margin-right: 8px;margin-left: 30px;"-->
                <!--                          @keyup.enter.native="search()"-->
                <!--                          clearable></el-input>-->
                <!--                <el-button class="el-button" size="mini" round plain type="primary" @click="search()">-->
                <!--                  搜索-->
                <!--                </el-button>-->
                <el-menu-item>
                  <el-input @keyup.enter.native="search()" @input="handleInputChange" style="width: 400px; margin-left: 60px;" clearable
                            placeholder="在这里输入你要找的软件" v-model="name" class="input-with-select">
                    <el-select class="input-select" v-model="nameId"
                               slot="prepend" placeholder="请选择" @change="handleSelectChange">
                      <el-option v-for="item in topName" :key="item.id" :value="item.id" :label="item.name"></el-option>
                    </el-select>
                    <el-button slot="append" icon="el-icon-search" @click="search()"></el-button>
                  </el-input>
                </el-menu-item>
              </el-menu>
            </div>
          </div>

          <div class="front-header-right">
            <div v-if="!userInfo" @click="showQRCode">
              <el-button size="mini" circle type="primary" icon="el-icon-user"></el-button>
              <el-button type="text"></el-button>
              <el-button class="login" type="text">登录</el-button>
            </div>

            <div v-else>
              <el-dropdown>
                <div class="front-header-dropdown">
                  <img :src="userInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'">
                  <div style="margin-left: 10px">
                    <span>{{ userInfo.username || 'username' }}
                    <i class="el-icon-arrow-down" style="margin-left: 2px"></i></span>
                  </div>
                </div>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="goToPerson">个人信息</el-dropdown-item>
                  <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>

              </el-dropdown>
            </div>
          </div>

        </div>

      </div>
    </div>
    <!--主体-->
    <div class="main-body">
      <router-view ref="child" @update:user="updateUser"/>
    </div>

    <!-- 使用全局组件 -->
    <ContactService></ContactService>

    <!-- 遮罩层 -->
    <div v-if="showQRCodeModal" class="overlay"></div>
    <!-- 模态框容器 -->
    <div class="qrcode-login" v-if="showQRCodeModal">
      <div style="display: flex;flex-direction: row">
        <!--        <img src="@/assets/imgs/front-logo.png"-->
        <!--             style="height: 30px;width: 30px;border-radius: 30px;margin: 6px 5px"/>-->
        <h2 style="font-weight: bold;font-size: 18px;margin-top: 10px">助教下载站</h2>
      </div>

      <div class="qrcode-modal">
        <!-- 关闭按钮 -->
        <el-button type="text" class="close-btn" @click="closeQRCodeModal" icon="el-icon-close"></el-button>
        <!-- 显示二维码图片 -->
        <img class="qrcode-img" :src="data.QRImageUrl" alt="二维码"/>
      </div>
      <p style="margin: 10px 0;text-align: center">微信扫码，授权登录</p>
      <span style="text-align: center;margin-top: 50px">登录即表示已阅读并同意《<el-button @click="toContact()"
                                                                                          type="text">用户协议</el-button>》和《<el-button
          @click="toPrivate()" type="text">隐私政策</el-button>》</span>
    </div>

  </div>

</template>

<script>

export default {
  name: "FrontLayout",

  data() {
    return {
      top: '',
      name: '',
      nameId: '分类',
      scale: 1,  // 初始缩放比例为 1，即原始大小
      activeMenuIndex: '/',   // 用于存储当前激活的菜单项
      erweima: '',
      ticket: '',
      showQRCodeModal: false, // 控制模态框的显示
      refreshInterval: null, // 刷新二维码的定时器
      checkStatusInterval: null, // 检查扫码状态的定时器
      data: '',
      userInfo: JSON.parse(localStorage.getItem('userInfo')),
      token: localStorage.getItem('token'),
      drawer: false,
      direction: 'rtl',
      screenHeight: 0,
      topName: [],
      topName1: '',
      topName2: '',
      allMenuItems: [
        {name: '首页', index: '/front/homeFront'},
        {name: 'a', index: '/front/drive'},
        {name: 'b', index: '/front/typeface'},
        {name: '关于我们', index: '/front/contact'},
      ],
      category: '分类',
    }
  },
  computed: {
    // 将菜单项分为主要菜单项和更多菜单项
    mainMenuItems() {
      return this.allMenuItemsComputed.slice(0, 3); // 假设前三个是主要菜单项
    },
    moreMenuItems() {
      return this.allMenuItemsComputed.slice(3); // 其余的是更多菜单项
    },
    allMenuItemsComputed() {
      return this.allMenuItems.map((item, index) => {
        if (index === 1) {
          return {...item, name: this.topName1};
        } else if (index === 2) {
          return {...item, name: this.topName2};
        }
        return item;
      });
    },
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.name === 'DriveClick' || to.name === 'DriveDetail') {
        vm.activeMenuIndex = '/front/drive';
      } else if (to.name === 'FaceClick' || to.name === 'FaceDetail') {
        vm.activeMenuIndex = '/front/typeface';
      } else if (to.name === 'Success') {
        vm.activeMenuIndex = '/front/feedBack';
      } else if (to.name === 'HomeClick' || to.name === 'Person' || to.name === 'HomeDetail' || to.name === 'Search' || to.name === 'Download' || to.name === 'Empty' || to.name === 'FeedBack') {
        vm.activeMenuIndex = '/front/homeFront';
      } else {
        vm.activeMenuIndex = to.path;
      }
    });
  },
  beforeRouteUpdate(to, from, next) {
    if (to.name === 'DriveClick' || to.name === 'DriveDetail') {
      this.activeMenuIndex = '/front/drive';
    } else if (to.name === 'FaceClick' || to.name === 'FaceDetail') {
      this.activeMenuIndex = '/front/typeface';
    } else if (to.name === 'HomeClick' || to.name === 'Person' || to.name === 'HomeDetail' || to.name === 'Search' || to.name === 'Download' || to.name === 'Empty' || to.name === 'FeedBack') {
      this.activeMenuIndex = '/front/homeFront';
    } else {
      this.activeMenuIndex = to.path;
    }
    next();
  },
  watch: {
    // 监听路由变化
    // $route(to, from) {
    //   // 当路由跳转到 homeClick 页面时，设置首页为激活状态
    //   if (to.name === 'HomeClick' || to.name === 'HomeDetail' || to.name === 'Search') {
    //     this.activeMenuIndex = '/front/homeFront';
    //   } else {
    //     // 否则，使用当前路由路径作为激活状态
    //     this.activeMenuIndex = to.path;
    //   }
    // },
  },
  created() {
    // 在组件创建时，初始化 activeMenuIndex
    this.activeMenuIndex = this.$route.path;
    this.load()
  },
  mounted() {
    // 监听滚轮事件
    window.addEventListener('wheel', this.handleWheelEvent);
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('wheel', this.handleWheelEvent);

    this.closeQRCodeModal(); // 确保在组件销毁前关闭模态框并清除定时器
  },
  methods: {
    load() {
      this.$request.get('/apis/downCategories/type').then(res => {
        this.topName = res.data
        this.topName1 = res.data[0].name
        this.topName2 = res.data[1].name
      })
    },
    toContact() {
      this.$router.push({
        name: 'Contact',
        query: {
          activeIndex: 1
        }
      })
      this.showQRCodeModal = false
    },
    toPrivate() {
      this.$router.push({
        name: 'Contact',
        query: {
          activeIndex: 3
        }
      })
      this.showQRCodeModal = false
    },
    loadUserInfo() {
      const token = this.getToken();
      if (token) {
        this.$request.get('/apis/user/info', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        }).then(res => {
          localStorage.setItem("userInfo", JSON.stringify(res))  // 存储用户数据
          window.location.reload()
        })
        // } else if (res.status === 401) { // 检查是否因为token过期而返回401状态码
        //   this.$message.error('Token expired, please log in again.');
        //   this.showQRCode(); // 显示二维码或其他登录方式
      } else {
        this.$message.error('No token found');
        this.showQRCode();
      }
    },
    getToken() {
      return localStorage.getItem('token');
    },
    showQRCode() {
      this.showQRCodeModal = true; // 显示模态框
      this.fetchQRCode(); // 请求二维码数据

      // 设置每60秒刷新二维码的定时器
      this.refreshInterval = setInterval(() => {
        this.fetchQRCode(); // 重新获取二维码
      }, 60000); // 60秒

      // 设置每2秒检查扫码状态的定时器
      this.checkStatusInterval = setInterval(() => {
        if (this.data.ticket) {
          this.checkScanStatus(this.data.ticket);
        }
      }, 2000);
    },
    closeQRCodeModal() {
      this.showQRCodeModal = false; // 关闭模态框
      // 清除所有定时器
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
        this.refreshInterval = null;
      }
      if (this.checkStatusInterval) {
        clearInterval(this.checkStatusInterval);
        this.checkStatusInterval = null;
      }
    },
    fetchQRCode() {
      this.$request.get('/wx/getQR').then(res => {
        this.data = res.data
        // this.erweima = res.data.QRImageUrl // 更新组件的 erweima 数据
        // this.ticket = res.data.ticket
      })
    },
    checkScanStatus() {
      this.$request.get(`/wx/login/status?ticket=${this.data.ticket}`).then(res => {
        if (res.msg === 'failed') {
          // 扫码失败或未关注
          // this.$message.error('扫码失败或未关注公众号，请重新尝试！');
        } else {
          // 关闭模态框
          this.closeQRCodeModal()
          // 显示登录成功提示
          this.$message.success('登录成功！')
          // this.token = response.data.msg
          // const token = response.data.msg; // 或者可能是 response.data.msg，但通常 msg 是状态信息，不是 token
          // 将 token 存储到 localStorage
          localStorage.setItem("token", (res.msg))
          this.loadUserInfo()
        }
      })
    },
    handleWheelEvent(event) {
      // 检查是否按下了Ctrl键
      if (event.ctrlKey) {
        // 防止页面的默认缩放行为
        // event.preventDefault();

        // 判断滚轮方向
        if (event.deltaY < 0) {
          // 滚轮向上滚动，放大页面
          this.scale = Math.min(this.scale + 0.1, 2);  // 最大放大到2倍
        } else {
          // 滚轮向下滚动，缩小页面
          this.scale = Math.max(this.scale - 0.1, 0.5);  // 最小缩小到0.5倍
        }
      }
    },
    handleSelectChange() {
      this.search()
    },
    handleInputChange() {
      this.search()
    },
    search() {
      this.$router.push({
        name: 'Search',
        query: {
          name: this.name,
          nameId: this.nameId,
        } // 直接传递
      });
    },
    updateUser() {
      this.userInfo = localStorage.getItem('userInfo') || '{}'   // 重新获取下用户的最新信息
    },
    // 退出登录
    logout() {
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      this.$router.push("/front/homeFront");
      this.$message.success('退出登录成功！')
      window.location.reload()
    },
    goToPerson() {
      this.$router.push('/front/person')
    },
  }

}
</script>

<style scoped>

.front-header {
  display: flex;
  height: 60px;
  line-height: 60px;
  border-bottom: 1px solid #eee;
  background: white;
  position: sticky;
  z-index: 99;
  top: 0;
}

.front-header-left img, .front-header-dropdown img {
  width: 40px;
  height: 40px;
  border-radius: 50%
}

.front-header-left {
  width: 180px;
  display: flex;
  align-items: center;
  padding-left: 10px;
}

.front-header-left img, .front-header-dropdown img {
  width: 40px;
  height: 40px;
  border-radius: 50%
}

.front-header-left .title {
  flex: 1;
  color: #355476;
  cursor: pointer;
  margin-left: 10px;
  font-size: 20px;
  font-weight: bold;
}

.front-header-center {
  flex: 1;
}

.rounded-input /deep/ .el-input__inner {
  border-radius: 30px;
  background-color: #f2f8fe;
}

.scalable-container {
  /* 确保缩放时容器本身不会改变大小 */
  width: 100%;
  height: 100%;
  transform-origin: top left;
  position: sticky;
  top: 0;
  z-index: 100;
}

.main-content {
  width: 1200px; /* 设置最大宽度 */
  margin: 0 auto; /* 居中显示 */
}

.qrcode-login {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.qrcode-modal {
  margin: 60px 10px 0 0;
  text-align: center;
  align-items: center;
}

.qrcode-img {
  border: 1px solid #e0e0e0;
  text-align: center;
  width: 200px;
  height: 200px;
  padding: 5px;
}

/deep/ .el-icon-user {
  font-size: 20px;
}

.login {
  color: black;
  font-size: 13px;
}

/deep/ .el-button [class*=el-icon-] + span {
  margin-left: 8px;
}

.close-btn {
  position: absolute; /* 绝对定位 */
  top: 10px; /* 距离顶部10px */
  right: 16px; /* 距离右边10px */
  z-index: 1001; /* 确保关闭按钮在模态框内容的上方 */
  border: none;
  font-size: 25px;
  color: black;
}

.front-header-right {
  width: 200px;
  padding-right: 20px;
  text-align: right;
}

.front-header-dropdown {
  display: flex;
  align-items: center;
  justify-content: right;
//position: relative; cursor: pointer;
}

.el-dropdown-menu {
  //position: absolute !important;
  //top: 52px !important;
  //left: 76% !important;
}

.input-select {
  width: 100px;
  color: #333333;
  //position: relative;

  /deep/ .el-select-dropdown {
    //position: absolute !important;
    //top: 52px !important;
    //left: 76% !important;
  }
}

/deep/ .el-button + .el-button {
  margin-left: 0px;
}

/* 遮罩层样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 灰色背景，透明度 50% */
  z-index: 1000;
}

</style>